package top.ckxgzxa.powerfailurewarning

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Uri
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.core.app.ActivityCompat
import android.Manifest

class MainActivity : ComponentActivity() {

    private lateinit var wifiReceiver: WifiReceiver
    private var mediaPlayer: MediaPlayer? = null

    private lateinit var volumeReceiver: VolumeReceiver
    private lateinit var audioManager: AudioManager

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_layout)

        wifiReceiver = WifiReceiver()
        registerReceiver(wifiReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))


        audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager

        volumeReceiver = VolumeReceiver()
        val filter = IntentFilter()
        filter.addAction("android.media.VOLUME_CHANGED_ACTION")
        registerReceiver(volumeReceiver, filter)

        val startButton: Button = findViewById(R.id.button1)
        startButton.setOnClickListener {
            // 改变监听服务
            if (startButton.text == "开始监听") {
                Toast.makeText(this@MainActivity, "开始监听！", Toast.LENGTH_SHORT).show()
                startButton.text = "停止监听"
                // 判定已定义的wifiReceiver监听器是否注册, 如果未注册, 则注册
//                registerReceiver(wifiReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))

                // 判定当前WiFi是否已连接
                if (getCurrentWiFiSSID(this@MainActivity) != "Xiaomi_5215") {
                    // WiFi网络已连接，但不是你期望的网络，触发报警
                    triggerAlarm()
                } else {
                    stopAlarm()
                }


            } else {
                Toast.makeText(this@MainActivity, "停止监听！", Toast.LENGTH_SHORT).show()
                startButton.text = "开始监听"
//                unregisterReceiver(wifiReceiver)
                stopAlarm()
            }

        }

//        val stopButton: Button = findViewById(R.id.button2)
//        stopButton.setOnClickListener {
//            // 停止监听服务
//            Toast.makeText(this@MainActivity, "停止监听！", Toast.LENGTH_SHORT).show()
//
//            stopAlarm()
//            releaseMediaPlayer()
//        }
    }



    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(wifiReceiver)
        unregisterReceiver(volumeReceiver)
        releaseMediaPlayer()
    }

    private inner class WifiReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val connManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkInfo: NetworkInfo? = connManager.activeNetworkInfo

            if (networkInfo != null && networkInfo.type == ConnectivityManager.TYPE_WIFI) {
//                // WiFi 连接状态改变
//                val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
//                val wifiInfo: WifiInfo = wifiManager.connectionInfo
//
//                // 使用 getSSID() 方法获取当前连接的 WiFi SSID
//                val currentSSID: String = wifiInfo.ssid.replace("\"", "")  // 去除获取到的SSID两侧的引号

                var currentSSID = getCurrentWiFiSSID(context)

                // 弹窗ssid
                Toast.makeText(this@MainActivity, currentSSID, Toast.LENGTH_SHORT).show()

                // 判断当前连接的 WiFi 是否是你期望的网络并且此时未处于报警状态
                if (!currentSSID.equals("Xiaomi_5215") && mediaPlayer == null) {
                    // WiFi网络已连接，但不是你期望的网络，触发报警
                    triggerAlarm()
                } else {
                    stopAlarm()
                }
            } else {
                // WiFi断开连接，触发报警
                triggerAlarm()
            }
        }
    }

    private inner class VolumeReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action.equals("android.media.VOLUME_CHANGED_ACTION")) {
                // 获取当前音量
                val currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)

                // 获取最大音量
                val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)

                // 如果当前音量小于最大音量，将音量调至最大
                if (currentVolume < maxVolume) {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0)
                }
            }
        }
    }

    private fun triggerAlarm() {
//        callMe()
        val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
        val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        var currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)

        // 逐步增加音量，直到达到最大音量
        while (currentVolume < maxVolume) {
            currentVolume++
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0)
            // 可以添加适当的延时，以调整音量增加的速度
            Thread.sleep(100)
        }

        // 在这里可以添加其他触发报警的逻辑，例如播放音频、显示通知等

        // 最后，播放系统默认的警告铃声
        try {
            mediaPlayer = MediaPlayer.create(this@MainActivity, R.raw.alarm)
            mediaPlayer?.setVolume(1.0f, 1.0f)

            // 设置循环播放
            mediaPlayer?.isLooping = true
            mediaPlayer?.start()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        // 在这里可以使用其他方式提醒用户，例如弹出一个对话框或者发送通知
        Toast.makeText(this@MainActivity, "WiFi断开连接！", Toast.LENGTH_SHORT).show()
    }


    private fun stopAlarm() {
        // 停止音频播放
        mediaPlayer?.stop()
        releaseMediaPlayer()
    }

    private fun releaseMediaPlayer() {
        // 释放MediaPlayer占用的资源
        mediaPlayer?.release()
        mediaPlayer = null
    }

    /**
     * 获取当前连接的WiFi的SSID
     *
     * @param context 上下文
     * @return 当前连接的WiFi的SSID
     */
    private fun getCurrentWiFiSSID(context: Context): String? {
        val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val wifiInfo: WifiInfo = wifiManager.connectionInfo
        return wifiInfo.ssid.replace("\"", "")
    }


    private fun callMe() {
        // 替换为你想要拨打的电话号码
        val phoneNumber = "xxxx"

        // 在代码中创建一个Intent对象，指定其action为Intent.ACTION_CALL，并设置其data为目标号码的Uri
        val intent = Intent(Intent.ACTION_CALL)
        intent.data = Uri.parse("tel:$phoneNumber")

        // 在Android 6.0及以上的版本中，您还需要在代码中动态申请拨打电话的权限，以确保用户同意您的应用拨打电话。您可以使用ActivityCompat.requestPermissions()方法来申请权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // Permission not granted, request it
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE), 100)
        } else {
            // Permission already granted, call phone
            startActivity(intent)
        }

    }


}
